package org.tsinghua.air.xls;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.tsinghua.air.common.Constant.Database;
import org.tsinghua.air.common.Constant.Xls;

public class XlsHandler {

	public static void readFile(String path) throws Exception {
		HSSFWorkbook wb = null;
		try {
			File file = new File(path);
			FileInputStream fs = new FileInputStream(file);
			wb = new HSSFWorkbook(fs);
			Database db = Xls.nameToTable(file.getName().split("[.]")[0]);
			if (db != null) {
				// read single sheet file
				HSSFSheet sheet = wb.getSheetAt(0);
				read(sheet, db);
			} else {
				for (int k = 0; k < wb.getNumberOfSheets(); k++) {
					HSSFSheet sheet = wb.getSheetAt(k);
					db = Xls.nameToTable(sheet.getSheetName());
					if (db != null) {
						read(sheet, db);
					}
				}
			}
		} finally {
			if (wb != null)
				wb.close();
		}
	}

	private static void read(HSSFSheet sheet, Database db) {
		int rows = sheet.getPhysicalNumberOfRows();

		if (rows < 2) //no data
			return;

		HSSFRow row0 = sheet.getRow(0);
		int cells = row0.getPhysicalNumberOfCells();
		ArrayList<String> years = new ArrayList<String>();
		for (int i=1; i<cells; i++){
			years.add( row0.getCell(i).getStringCellValue());
		}
	}

}
